package com.feng.system.controller;

import com.feng.common.api.ResponseResult;
import com.feng.common.utils.FileUtil;
import com.feng.common.validation.groups.Insert;
import com.feng.common.validation.groups.Update;
import com.feng.system.dto.UserParam;
import com.feng.system.dto.UserQueryParam;
import com.feng.system.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.groups.Default;
import java.util.Set;

/**
 * @author Feng
 * @since 2022/4/15 12:08
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation("根据ID获取用户角色列表")
    @GetMapping("/roles/{id}")
    @PreAuthorize("@er.check('user:list')")
    public ResponseResult getRolesById(@PathVariable Long id) {
        return ResponseResult.success(userService.getRolesById(id));
    }

    @ApiOperation("条件查询用户信息(不包括角色列表)")
    @GetMapping("/search")
    @PreAuthorize("@er.check('user:list')")
    public ResponseResult search(UserQueryParam param,
                                     @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        return ResponseResult.success(userService.search(param, pageNum, pageSize));
    }

    @ApiOperation("添加单个用户")
    @PostMapping
    @PreAuthorize("@er.check('user:add')")
    public ResponseResult add(@RequestBody @Validated({Default.class, Insert.class}) UserParam userParam) {
        userService.addUser(userParam);
        return ResponseResult.success();
    }

    @ApiOperation("修改单个用户")
    @PutMapping
    @PreAuthorize("@er.check('user:update')")
    public ResponseResult update(@RequestBody @Validated({Default.class, Update.class}) UserParam userParam) {
        userService.updateUser(userParam);
        return ResponseResult.success();
    }

    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@er.check('user:delete')")
    public ResponseResult delete(@RequestBody Set<Long> ids) {
        userService.deleteUser(ids);
        return ResponseResult.success();
    }

    @ApiOperation("修改头像")
    @PostMapping("/center/updateAvatar")
    public ResponseResult updateAvatar(@RequestParam MultipartFile avatar) {
        userService.updateAvatar(avatar);
        return ResponseResult.success();
    }
}
